package com.aiyige.utils.removal.dao;

import android.text.TextUtils;

import com.aiyige.MyApp;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.removal.RemovalHandler;
import com.aiyige.utils.removal.entity.CacheTaskEntity;
import com.aiyige.utils.removal.entity.VideoCacheEntity;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 缓存视频
 * Created by UQIANTU on 16/10/26.
 */

public class VideoCacheDao {
    private com.aiyige.utils.removal.ReDBHelper ReDBHelper;
    private Dao dao;

    public VideoCacheDao() {
        ReDBHelper = ReDBHelper.getHelper(MyApp.getAppContext());
        dao = ReDBHelper.getDao(VideoCacheEntity.class);
    }

    /**
     * 添加视频缓存
     *
     * @param info
     */
    public void addVideoCache(VideoCacheEntity info) {
        try {
//            if (info != null && info.getUrl() != null && isHasCached(info.getUrl())) {
//                return;
//            }
            dao.create(info);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否已缓存
     *
     * @param info
     * @return
     */
    public boolean isHasCached(VideoCacheEntity info) {
        return isHasCached(info.getUrl());
    }

    public boolean isHasCached(String url) {
        try {
            List<VideoCacheEntity> list = dao.queryForEq("url", url);
            if (null != list && !list.isEmpty()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 是否已缓存
     *
     * @param title
     * @param url
     * @return
     */
    public boolean isHasCached(String title, String url) {
        if (TextUtils.isEmpty(title)) {
            return false;
        }
        try {
            List<VideoCacheEntity> list = dao.queryBuilder().where().eq("url", url).and().eq("title", title).query();
            if (null != list && !list.isEmpty()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 是否本地视频已缓存
     *
     * @param title
     * @param
     * @return
     */
    public boolean isHasLocalCache(String title, String path) {
        if (TextUtils.isEmpty(title)) {
            return false;
        }
        try {
            List<VideoCacheEntity> list = dao.queryBuilder().where().eq("path", path).and().eq("title", title).query();
            if (null != list && !list.isEmpty()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 是否本地视频已缓存
     *
     * @param path
     * @param
     * @return
     */
    public boolean isHasLocalCache(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        try {
            List<VideoCacheEntity> list = dao.queryBuilder().where().eq("path", path).query();
            if (null != list && !list.isEmpty()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 更新缓存
     *
     * @param info
     */
    public void updateVideoCache(VideoCacheEntity info) {
        if (info.getLocalId() == 0) {
            VideoCacheEntity cache = find(info.getUrl());
            if (null != cache) {
                info.setLocalId(cache.getLocalId());
            } else {
                addVideoCache(info);
                return;
            }
        }
        try {
            dao.update(info);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除缓存
     *
     * @param info
     */
    public void removeVideoCache(VideoCacheEntity info) {
        try {
            dao.delete(info);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public VideoCacheEntity find(String url) {
        try {
            List<VideoCacheEntity> list = dao.queryForEq("url", url);
            if (null != list && !list.isEmpty()) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询缓存
     *
     * @return
     */
    public List<VideoCacheEntity> queryVideoCaches() {
        List<VideoCacheEntity> list = new ArrayList<VideoCacheEntity>();

        try {
            List<VideoCacheEntity> data = dao.queryBuilder().orderBy("localId", false).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询未下载完的缓存
     *
     * @return
     */
    public List<VideoCacheEntity> queryUnDownloadCache() {
        List<VideoCacheEntity> list = new ArrayList<VideoCacheEntity>();
        try {
            List<VideoCacheEntity> data = dao.queryBuilder().where().eq("status", 0).or().eq("status", 3).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询已下载完的缓存
     *
     * @return
     */
    public List<VideoCacheEntity> queryDownloadedCache() {
        List<VideoCacheEntity> list = new ArrayList<VideoCacheEntity>();
        try {
            List<VideoCacheEntity> data = dao.queryBuilder().where().eq("status", 1).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询缓存视频
     *
     * @return
     */
    public List<VideoCacheEntity> queryCacheVideoId(String videoId) {
        List<VideoCacheEntity> list = new ArrayList<>();
        try {
            List<VideoCacheEntity> data = dao.queryBuilder().where().eq("videoId", videoId).query();
            if (null != data) {
                list.addAll(data);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询是否已缓存
     *
     * @param videoId
     * @return
     */
    public List<VideoCacheEntity> queryCacheVideoByServerCode(String videoId) {
        try {
            List<VideoCacheEntity> data = dao.queryBuilder().where().eq("videoId", videoId).query();
            return data;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean delete(String videoId) {
        try {
            List<VideoCacheEntity> data = dao.queryBuilder().where().eq("videoId", videoId).query();
            if (data != null && !data.isEmpty()) {
                dao.delete(data);
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 根据ServerCode删除
     *
     * @param serverCodeList
     */
    public int deleteServerCodeByUserId(List<String> serverCodeList) {
        if (ListUtil.isEmpty(serverCodeList)) {
            return 0;
        }
        String userId = AccountUtil.getCurrentUser().getId();
        int successCount = 0;
        for (String serverCode : serverCodeList) {
            try {
                DeleteBuilder<CacheTaskEntity, Integer> deleteBuilder = dao.deleteBuilder();
                if (RemovalHandler.isDebug) {
                    deleteBuilder.where().eq("serverCode", serverCode);
                } else {
                    deleteBuilder.where().eq("serverCode", serverCode)
                            .and().eq("userId",userId);
                }
                int success = deleteBuilder.delete();
                if (success > 0) {
                    successCount++;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return successCount;
    }


    public int delete(List<String> videoIds) {
        int count = 0;
        try {
            if (ListUtil.isEmpty(videoIds)) {
                return count;
            }
            if (dao != null) {
                count = dao.deleteIds(videoIds);
            }
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * ״ 查询缓存状态̬
     *
     * @param url
     * @return
     */
    public int queryCacheStatus(String url) {
        try {
            List<VideoCacheEntity> list = dao.queryForEq("url", url);
            if (null != list && !list.isEmpty()) {
                return list.get(0).getStatus();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 设置下载中的缓存状态为未下载完
     */
    public void setStatusUnDownLoad() {
        try {
            dao.updateRaw("UPDATE 'videoCache' SET status = 3 WHERE status = 2;");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取缓存总数
     *
     * @return
     */
    public int getCacheCount() {
        int count = 0;
        try {
            count = Long.valueOf(dao.countOf()).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
